<?php
/**
 * 费用及发票逻辑
 * 作者：MYL
 */
namespace app\api\controller;

use app\api\model\InvoiceModel;
use app\api\model\OrderModel;
use app\api\model\UserModel;
use think\Db;

class Invoice extends Base
{
    /**
     * 费用中心
     */
    public function costList()
    {
        if ($this->request->isPost()) {
            $data = array();
            $user_id = I('post.user_id');

            $where['user_id'] = $user_id;
            $rs = UserModel::inquire($where);
            $data['user_money'] = $rs['user_money']; //用户总资产
            $where['order_status'] = 0;
            $where['pay_status'] = 0;
            $row = OrderModel::manyData($where);
            foreach ($row as $val) {
                $data['goods_price']+= $val['goods_price'];//用户未付款（总金额）
            }
            ajaxReturn(['status' => 1, 'msg' => '获取成功', 'result' => $data]);
        } else {
            ajaxReturn(['status' => -1, 'msg' => '请求错误，请重新请求！']);
        }
    }

    /**
     * 费用明细
     * 按时间查询账单信息
     */
    public function chargeDetails()
    {

    }


    /**------------------------------------------------发票逻辑-----------------------------------------------------**/
    /**
     * 可开发票总金额
     */
    public function invoiceTotal()
    {
        if ($this->request->isPost()) {
            $data = array();
            $user_id = I('post.user_id');

            //用户订单已支付的总金额
            $where['pay_status'] = 1;
            $where['user_id'] = $user_id;
            $where['invoice_status'] = 0;
            $row = M('order')->field('goods_price')->where($where)->select();
            if ($row) {
                foreach ($row as $val) {
                    $data['goods_price']+= $val['goods_price'];//用户已付款（总金额）
                }
                ajaxReturn(['status' => 1, 'msg' => '获取成功', 'result' => $data]);
            } else {
                ajaxReturn(['status' => 1, 'msg' => '获取成功', 'result' => '0.00']);
            }
        } else {
            ajaxReturn(['status' => -1, 'msg' => '请求错误，请重新请求！']);
        }
    }

    /**
     * 可以申请发票的（订单列表）
     */
    public function applyInvoice()
    {
        if ($this->request->isPost()) {
            $user_id = I('post.user_id');
            $page = I("post.page", 1);

            //查询条件
            $category_id = I('category_id'); //分类ID
            $new_date = I('new_date'); //时间
            $arr = getCatGrandson($category_id); //获取某个商品分类的 儿子 孙子  重子重孙 的 id
            if ($category_id !='' && $category_id !=1) {
                $where['gc.id'] = ['IN' ,$arr];
            }
            if ($new_date) {
                $where["FROM_UNIXTIME(or.add_time,'%Y-%m-%d')"] = $new_date; //日期未实现
            }

            //用户订单已支付的总金额
            $row = M('order')->alias('or')
                ->field("or.order_id, or.order_sn, or.pay_status, or.goods_price, or.order_type, FROM_UNIXTIME(or.add_time,'%Y-%m-%d %H:%i:%s') as add_time, go.goods_name")
                ->join('order_goods og', 'or.order_id = og.order_id', 'LEFT')
                ->join('goods go' ,'og.goods_id = go.goods_id', 'LEFT')
                ->join('goods_category gc' ,'go.cat_id = gc.id', 'LEFT')
                ->where(['or.user_id' => $user_id, 'or.pay_status' => 1])
                ->where($where)
                ->order('or.order_id desc')
                ->page($page, 20)
                ->select();
            foreach ($row as $key =>$val) {
                if ($val['order_type']==1) {
                    $row[$key]['order_type'] = '新购';
                } else {
                    $row[$key]['order_type'] = '续费';
                }
            }
            if ($row) {
                ajaxReturn(['status' => 1, 'msg' => '获取成功', 'result' => $row]);
            } else {
                ajaxReturn(['status' => -1, 'msg' => '获取失败', 'result' => []]);
            }
        } else {
            ajaxReturn(['status' => -1, 'msg' => '请求错误，请重新请求！']);
        }
    }

    /**
     * 立即开票（列表）
     */
    public function immediatelyInvoice()
    {
        if ($this->request->isPost()) {
            $data['user_id'] = I('post.user_id');
            $data['order_id'] = I('post.order_id');
            $data['address_id'] = I('post.address_id');
            $data['invoice_money'] = I('post.invoice_money');
            $data['invoice_title'] = I('post.invoice_title');
            $data['invoice_desc'] = I('post.invoice_desc');
            $data['taxpayer'] = I('post.taxpayer');
            $data['ctime'] = time();
            $rs = Db::name('invoice')->insert($data);
            if (!empty($rs)) {
                ajaxReturn(['status' => 1, 'msg' => '提交成功，请耐性等待！']);
            } else {
                ajaxReturn(['status' => -1, 'msg' => '请求错误，请重新请求！']);
            }
        } else {
            ajaxReturn(['status' => -1, 'msg' => '请求错误2，请重新请求2！']);
        }
    }

    /**
     * 发票抬头
     */
    public function invoiceHeader()
    {
        $user_id = I('post.user_id');

        $where['user_id'] = $user_id;
        $row = InvoiceModel::whereGetOne($where);
        if ($row) {
            if ($row['invoice_type']==1) {
                $row['invoice_type'] = '增值税普通发票';
            } if ($row['invoice_type']==2) {
                $row['invoice_type'] = '企业增值税普通发票';
            } if ($row['invoice_type']==3) {
                $row['invoice_type'] = '增值税专发票';
            } if ($row['invoice_type']==4) {
                $row['invoice_type'] = '组织增值税普通发票';
            }
            ajaxReturn(['status' => 1, 'msg' => '获取成功', 'result' => $row]);
        } else {
            ajaxReturn(['status' => -1, 'msg' => '获取失败', 'result' => []]);
        }
    }

    /**
     * 发票抬头的增删改
     */
    public function invoceAddEdit()
    {
        $invoce_id    = I('post.invoce_id'); //发票抬头ID

        $map['user_id']      = I('post.user_id'); //用户ID
        $map['header_name']  = I('post.header_name'); //抬头名称
        $map['invoice_type'] = I('post.invoice_type'); //发票类型：1.增值税普通发票 2.企业增值税普通发票 3.增值税专发票 4.组织增值税普通发票
        $map['service'] = I('post.service'); //服务内容
        $map['tax_number']   = I('post.tax_number'); //税务登记证号
        $map['address']      = I('post.address'); //注册场所地址
        $map['fixed_telephone'] = I('post.fixed_telephone'); //注册固定电话
        $map['bank']         = I('post.bank'); //银行名称
        $map['bank_card']    = I('post.bank_card'); //银行卡号

        //判断是否有数据
        if (!empty($invoce_id)) {
            $rs = M('invoice_up')->where('id',$invoce_id)->update($map);
            if ($rs) {
                ajaxReturn(['status' => 1, 'msg' => '更新成功！']);
            } else {
                ajaxReturn(['status' => -1, 'msg' => '信息不能重复！']);
            }
        } else {
            $map['add_time'] = time();
            $rs = M('invoice_up')->insert($map);
            if ($rs) {
                ajaxReturn(['status' => 1, 'msg' => '新增成功！']);
            } else {
                ajaxReturn(['status' => -1, 'msg' => '新增失败！']);
            }
        }
    }

    /**-------------------------------------------工单接口----------------------------------------------------------**/
    /**
     * 正在进行中的工单个数
     */
    public function workConduct()
    {
        $user_id = I('post.user_id');
        $where['user_id'] = $user_id;
        $where['status'] = array('IN',array(0,1,2));
        $row = Db::name('work_order')->field("id")->where($where)->count();
        if ($row) {
            ajaxReturn(['status' => 1, 'msg' => 'Success！', 'data'=>$row]);
        } else {
            ajaxReturn(['status' => -1, 'msg' => 'Error！', 'data'=>0]);
        }
    }
    /**
     * 工单列表(全部,进行中，已完成)
     */
    public function workList()
    {
        $user_id = I('post.user_id');
        $serviceState = I('post.serviceState');
        $page = I('post.page', 1);

        $where['user_id'] = $user_id;
        if ($serviceState == 2) {
            $where['status'] = array('IN',array(0,1,2));
        }
        if ($serviceState == 3) {
            $where['status'] = 3;
        }

        $row = Db::name('work_order')->field("*,FROM_UNIXTIME(add_time,'%Y-%m-%d') as add_time")->where($where)->page($page,20)->select();
        ajaxReturn(['status' => 1, 'msg' => '获取成功！', 'data'=>$row]);
    }

    /**
     * 工单列表详情
     */
    public function workDetails()
    {
        $id = I('get.wid'); //工单ID

        $prom_list = Db::name('work_order')->alias('w')
            ->field("w.*,FROM_UNIXTIME(add_time,'%Y-%m-%d %H:%i:%s') as add_time,u.nickname")
            ->join('users u','w.user_id = u.user_id','left')
            ->where('id',$id)
            ->find(); //工单问题
        $work = Db::name('work_record')->alias('wo')
            ->field("wo.*,FROM_UNIXTIME(add_time,'%Y-%m-%d %H:%i:%s') as add_time,u.nickname")
            ->join('users u','wo.wid = u.user_id','left')
            ->where('wid',$id)
            ->select(); //相关的评论信息
        $ping = Db::name('work_evaluation')->field("*,FROM_UNIXTIME(add_time,'%Y-%m-%d %H:%i:%s') as add_time")->where('wid',$id)->find(); //评论信息
        if (!empty($ping)) {
            if ($ping['is_solve']==1) {
                $ping['is_solve'] = '已解决';
            } else {
                $ping['is_solve'] = '未解决';
            }
            if(empty($ping['feedback'])) {
                $ping['feedback'] = '无建议和意见';
            }
        } else {
            $ping = 2;
        }


        ajaxReturn(['status' => 1, 'msg' => '获取成功！', 'prom_list'=>$prom_list, 'work'=>$work, 'ping'=>$ping]);

    }

    /**
     * 提交工单信息
     */
    public function workOrder()
    {
        $data = array();
        $data['cid'] = I('post.cid'); //分类ID
        $data['user_id'] = I('post.user_id'); //用户ID
        $data['description'] = I('post.description'); //问题描述
        $data['mobile'] = I('post.mobile'); //手机
        $data['mailbox'] = I('post.mailbox'); //邮箱
        $data['receiving'] = I('post.receiving'); //接收短信时间段：1.每日09:00-18:00 2.任何时间
        $data['status'] = 0; //状态：0.催办 1.待回复 2.已回复 3.已关闭
        $data['add_time'] = time();

        $rs = Db::name('work_order')->insert($data);
        if ($rs) {
            ajaxReturn(['status' => 1, 'msg' => '提交成功，请耐心等待！']);
        } else {
            ajaxReturn(['status' => -1, 'msg' => '提交失败，请重新提交！']);
        }
    }

    /**
     * 用户继续留言
     */
    public function message()
    {
        $data = array();
        $data['wid'] = I('post.wid'); //工单ID
        $data['user_id'] = I('post.user_id'); //用户ID
        $data['comment'] = I('post.comment'); //问题描述
        $data['add_time'] = time();

        $rs = Db::name('work_record')->insert($data);
        if ($rs) {
            M('work_order')->where('id',$data['wid'])->update(['status'=>1]);
            ajaxReturn(['status' => 1, 'msg' => '留言成功！']);
        } else {
            ajaxReturn(['status' => -1, 'msg' => '留言失败，请重新提交留言！']);
        }
    }

    /**
     * 用户关闭工单
     */
    public function workClose()
    {
        $data = array();
        $data['wid'] = I('post.wid'); //工单ID
        $data['user_id'] = I('post.user_id'); //用户ID
        $data['comment'] = '用户移动端关闭工单！'; //问题描述
        $data['add_time'] = time();

        //新增工单信息
        $rs = Db::name('work_record')->insert($data);
        if ($rs) {
            M('work_order')->where('id',$data['wid'])->update(['status'=>3]);
            ajaxReturn(['status' => 1, 'msg' => '关闭成功！']);
        } else {
            ajaxReturn(['status' => -1, 'msg' => '关闭失败！']);
        }
    }

    /**
     * 用户评价工单服务
     */
    public function workService()
    {
        $data['wid'] = I('wid'); //工单ID
        $data['user_id'] = I('post.user_id'); //用户ID
        $data['evaluation'] = I('post.evaluation'); //评价星级
        $data['praise'] = I('post.praise'); //评价标语
        $data['is_solve'] = I('post.is_solve'); //是否解决：1.已解决 2.未解决
        $data['feedback'] = I('post.feedback'); //评价反馈的问题
        $data['add_time'] = time();

        $rs = Db::name('work_evaluation')->insert($data);
        if ($rs) {
            M('work_order')->where('id',$data['wid'])->update(['status'=>4]);
            ajaxReturn(['status' => 1, 'msg' => '评价成功！']);
        } else {
            ajaxReturn(['status' => -1, 'msg' => '评价失败！']);
        }
    }


}